package timing.ukulele.third.controller.weixin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpFreePublishService;
import me.chanjar.weixin.mp.bean.freepublish.WxMpFreePublishList;
import org.springframework.web.bind.annotation.*;
import timing.ukulele.common.data.ResponseData;
import timing.ukulele.data.third.data.weixin.WxDraftDTO;
import timing.ukulele.third.config.mp.WxMpConfiguration;

/**
 * 微信发布
 */
@Slf4j
@RestController
@RequestMapping("/weixin/wxPublished")
public class WxFreePublishController {

    /**
     * /published/deletePublish
     * @param id
     * @param appId
     * @return
     */
	@Operation(summary = "删除已发布文章")
	@DeleteMapping("/deletePublish")
	public ResponseData<Boolean> deletePublish(@RequestParam("id") String id,
                                      @RequestParam("appId") String appId) {
		WxMpFreePublishService wxMpFreePublishService = WxMpConfiguration.getMpServiceByAppId(appId).getFreePublishService();
		try {
			return ResponseData.success(wxMpFreePublishService.deletePushAllArticle(id));
		} catch (WxErrorException e) {
            return ResponseData.error("删除已发布文章失败" + e.getMessage());
		}
	}

    /**
     * /published/page
     * @param wxDraftDTO
     * @return
     */
    @Operation(summary = "分页查询发布成功文章列表")
	@PostMapping("/page")
	public ResponseData<IPage> page(@RequestBody WxDraftDTO wxDraftDTO) {
        try {
            WxMpFreePublishService wxMpFreePublishService = WxMpConfiguration
                    .getMpServiceByAppId(wxDraftDTO.getAppId()).getFreePublishService();
            int count = wxDraftDTO.getPageSize();
            int offset = wxDraftDTO.getCurrent() * count - count;
            WxMpFreePublishList wxMpFreePublishList = wxMpFreePublishService.getPublicationRecords(offset, count);
            Page page = new Page();
            page.setTotal(wxMpFreePublishList.getTotalCount());
            page.setSize(wxDraftDTO.getPageSize());
            page.setRecords(wxMpFreePublishList.getItems());
            return ResponseData.success(page);
        } catch (Exception e) {
            return ResponseData.error("分页查询发布成功文章列表失败" + e.getMessage());
        }
	}

}
